package com.lb.websocket.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: liubin
 *
 * @author liubin
 * Date: 2018-04-25
 * Time: 下午 6:24
 */
@Component
@ServerEndpoint("/webSocket")
@Slf4j
public class WebSocket {

    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSocketsSet = new CopyOnWriteArraySet<WebSocket>();

    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketsSet.add(this);
        log.info("有新的链接进入，总数为"+webSocketsSet.size());
    }

    @OnClose
    public void onClose(Session session){
        webSocketsSet.remove(this);
        log.info("链接退出，总数为"+webSocketsSet.size());
    }

    @OnMessage
    public void onMessage(String message){
        log.info("收到客户端发来的消息",message);
    }

    public static void sendMessage(String message){
        for(WebSocket webSocket : webSocketsSet){
            log.info("广播消息");
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
